const BaseRest = require('./rest.js');

module.exports = class extends BaseRest {
	async getAction() {
		let data = {};
		const map = {};
		// 获取详情
		if(this.id) {
			map.id = this.id;
			data = await this.modelInstance.where(map).find();
			
			data['roles'] = await this.modelInstance.getRoles(data.id);
			
			return this.success(data);
		}
		
		// 关键词
		const key = this.get('key');
		if(key) {
			map['title|path'] = ['like', '%' + key + '%'];
		}
		
		// 页码
		const page = this.get('page') || 1;
		
		if(this.get('all')) {
			data = await this.modelInstance.where(map).order('id asc').select();
			return this.success(data);
		}
		
		// 每页显示数量
		const pageSize = this.get('pageSize') || 10;
		
		// think.logger.debug(map);
		
		data = await this.modelInstance.where(map).page(page, pageSize).order('id asc').countSelect();
		
		for (const element of data.data) {
			element['roles'] = await this.modelInstance.getRoles(element.id);
		}
		
		return this.success(data);
	}
	
	/**
	 * 删除内容
	 * @return {[type]} [description]
	 */
	async deleteAction() {
		if(!this.id) {
			return this.fail(1001, '记录不存在');
		}
		
		// 需要处理成事物，保证信息一致
		// 删除角色关联信息
		const rows1 = await this.model('role_auth').where({
			resource_id: this.id
		}).delete();
		
		// 删除角色
		const rows = await this.modelInstance.where({
			id: this.id
		}).delete();
		if(rows) {
			// await this.hook('roleDelete', {id: this.id});
			return this.success({
				affectedRows: rows
			}, '删除成功');
		} else {
			return this.fail(1000, '删除失败');
		}
	}
	
	async postAction() {
		const data = this.post();
		
		// 添加标签
		if(this.post('resource_id') && this.post('role_id')) {
			data['id'] = think.uuid('v1');
			//查找缺省权限，复制过来
			const resource = await this.model('resource').where({id: this.post('resource_id')}).find();
			if(!think.isEmpty(resource)) {
				data['get'] = resource['get'];
				data['post'] = resource['post'];
				data['delete'] = resource['delete'];
				data['patch'] = resource['patch'];
				data['put'] = resource['put'];
			}
			
			const id = await this.model('role_auth').thenAdd(data, {
				role_id: this.post('role_id'),
				resource_id: this.post('resource_id')
			});
			
			if(id) {
				return this.success({id: id}, '资源授权成功');
			} else {
				return this.fail(1000, '资源授权失败');
			}
		}
		
		// 增加角色操作
		const id = await this.modelInstance.add(data);
		if(id) {
			return this.success({id: id}, '添加成功');
		} else {
			return this.fail(1000, '添加失败');
		}
	}
};
